package com.hnkywl.sts.action.base;

import com.hnkywl.sts.entity.base.Fj;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.service.base.FjService;
import com.hnkywl.sts.service.sys.YgService;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-4-4
 * Time: 下午5:26
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/base/fj")
public class FjAction extends SimpleActionSupport {
    private File file;
    private String fileFileName;

    private FjService fjService;

    private String url;

    private Long fjId;


    @Action("uploadFile")
    public void uploadFile() {
        String extName = StringUtils.EMPTY;//扩展名
        String nowTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//当前时间
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/uploads/";
        String savePath = ServletActionContext.getRequest().getRealPath("");
        savePath = savePath + "/uploads/";
        File dir = new File(savePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //获取扩展名
        if (fileFileName.lastIndexOf(".") >= 0) {
            extName = fileFileName.substring(fileFileName.lastIndexOf("."));
        }
        String newFileName = nowTime + extName;
        try {
            FileOutputStream fos = new FileOutputStream(savePath + "\\" + newFileName);
            FileInputStream fis = new FileInputStream(file);
            byte[] buffers = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffers)) != -1) {
                fos.write(buffers, 0, len);
            }
            fos.close();
            fis.close();
            Long fileId = saveFile(url, newFileName);
            this.renderJson("{'fileId':" + fileId + ",'fileName':'" + fileFileName + "'}");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存附件到数据库
     *
     * @param savePath
     * @param newFileName
     * @throws IOException
     */
    private Long saveFile(String savePath, String newFileName) throws IOException {
        Fj fj = new Fj();
        fj.setCcmc(fileFileName);
        fj.setWjlj(savePath + newFileName);
        fj.setWjm(newFileName);
        FileInputStream fis = new FileInputStream(file);
        fj.setWj(Hibernate.createBlob(fis));
        fj.setDeleted(0);
        fj.setDateCreated(new Date());
        fj.setLastUpdated(fj.getDateCreated());
        fj.setScsj(fj.getDateCreated());
        this.fjService.saveFj(fj);
        fis.close();
        return fj.getId();
    }

    @Action("downLoadFj")
    public String downLoadFj() {
        try {
            Fj fj = this.fjService.getFj(this.fjId);
            if (fj != null) {
                String fileName = StringUtils.EMPTY;
                // 终极解决文件名乱码
                if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                    fileName = new String(fj.getCcmc().getBytes("UTF-8"), "ISO8859-1");// firefox浏览器
                } else if (request.getHeader("User-Agent").toUpperCase()
                        .indexOf("MSIE") > 0) {
                    fileName = URLEncoder.encode(fj.getCcmc(), "UTF-8");// IE浏览器
                }
                URL httpUrl = new URL(fj.getWjlj());
                HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                InputStream inStream;
                try {
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        inStream = conn.getInputStream();
                    } else {
                        Blob fjFile = fj.getWj();
                        inStream = fjFile.getBinaryStream();
                    }
                } catch (java.net.ConnectException e) {
                    Blob fjFile = fj.getWj();
                    inStream = fjFile.getBinaryStream();
                }
                downLoadCellFile(inStream, response, fileName);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    @Action("downLoadLodop")
    public String downLoadLodop() {
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            InputStream inStream;
            inStream = conn.getInputStream();
            downLoadCellFile(inStream, response, fileFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void downLoadCellFile(InputStream inStream, HttpServletResponse response, String fileName) throws IOException {
        // 设置输出的格式
        response.reset();
        response.setContentType(" APPLICATION/OCTET-STREAM ");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        while ((len = inStream.read(b)) > 0)
            response.getOutputStream().write(b, 0, len);
        inStream.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    public void previewFj(InputStream inStream, HttpServletResponse response, String fileName) throws IOException {

    }

    @Action("deleteFj")
    public void deleteFj() {
        try {
            this.fjService.deleteFj(fjId);
            renderText("{\"statusCode\":\"200\", \"message\":\"删除附件成功\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public Long getFjId() {
        return fjId;
    }

    public void setFjId(Long fjId) {
        this.fjId = fjId;
    }

    public FjService getFjService() {
        return fjService;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    @Autowired
    public void setFjService(FjService fjService) {
        this.fjService = fjService;
    }
}
